var EnergyForm = function () {
  var EnergyModel = function (energy, deptProcessMap, isUsed) {
    BaseModel.call(this);
    var self = this;

    var fn = {
      initData: function (energy, deptProcessMap, isUsed) {
        if (energy === undefined) {
          energy = {};
          self.deptProcess = [];
          self.isUsed = false;
        } else {
          self.isUsed = isUsed;
          var deptProcessList = energy.workShopIdList;
          var deptProcessObj = _.find(deptProcessList, function (obj) {
            var processId = obj.processId;
            return !SysUtil.isEmpty(processId) && processId !== '0';
          });
          if (deptProcessObj === undefined) {
            self.deptProcess = [];
          } else {
            var processId = deptProcessObj.processId;
            var obj = deptProcessMap[processId];
            if (obj === undefined) {
              self.deptProcess = [];
            } else {
              self.deptProcess = [obj.deptId, obj.workshopId, obj.processId];
            }
          }
        }
        var fields = ['no', 'name', 'energyType', 'address', 'imgUrl'];
        self.setDataFromObj(energy, fields, '');

        var variableRatio = energy.variableRatio;
        if (SysUtil.isEmpty(variableRatio) || variableRatio === 0) {
          variableRatio = '';
        }
        self.variableRatio = variableRatio;
      },

      getDeptProcessData: function () {
        var deptProcess = self.deptProcess;
        if (deptProcess.length === 0) {
          return [];
        }

        var workshopId = deptProcess[1];
        var processId = deptProcess[2];
        return [{
          workShopId: workshopId,
          processId: processId
        }];
      }
    };

    this.checkValid = function () {
      var fields = ['no', 'name', 'energyType'];
      var code = this.checkRequiredFields(fields, true);
      if (code !== '') {
        return code;
      }

      if (this.energyType === 1) {
        if (SysUtil.isEmpty(this.variableRatio)) {
          return 'variableRatio';
        }
      }

      return '';
    };

    this.getObject = function () {
      var postData = {};
      var fields = ['no', 'name', 'energyType', 'address', 'imgUrl'];
      this.setPostData(postData, fields);

      if (this.energyType === 1) {
        postData.variableRatio = this.variableRatio;
      } else {
        postData.variableRatio = 0;
      }

      var deptProcessData = fn.getDeptProcessData();
      postData.workShopIdList = deptProcessData;
      return postData;
    };

    this.getUpdateObject = function () {
      var postData = {
        energyId: this.no,
        imgUrl: this.imgUrl
      };

      var fields = ['name', 'energyType', 'address'];
      this.setPostData(postData, fields);

      var deptProcessData = fn.getDeptProcessData();
      postData.workShopIdArray = JSON.stringify(deptProcessData);
      return postData;
    };

    fn.initData(energy, deptProcessMap, isUsed);
  };

  var template = /* html */ `
    <div class="energy-form" v-loading.fullscreen.lock="loading">
      <template v-if="energyForm!==null">
      <el-form label-width="80px" size="medium">
        <el-form-item :required="type==='add'" label="仪表编号">
          <el-input v-if="type==='add'" class="form-input" v-model="energyForm.no"></el-input>
          <span v-else>{{energyForm.no}}</span>
        </el-form-item>
        <el-form-item required label="仪表名称">
          <el-input class="form-input" v-model="energyForm.name"></el-input>
        </el-form-item>
        <el-form-item :required="!energyForm.isUsed" label="仪表类型">
          <el-select v-if="!energyForm.isUsed" class="form-input" v-model="energyForm.energyType">
            <el-option v-for="item in energyTypeList" :key="item.value" :value="item.value" :label="item.label">
            </el-option>
          </el-select>
          <span v-else>{{i18n.getMsg('energyMgr.energyType.'+energyForm.energyType)}}</span>
        </el-form-item>
        <el-form-item label="仪表位置">
          <el-input class="form-input" v-model="energyForm.address"></el-input>
        </el-form-item>
        <el-form-item v-if="energyForm.energyType===1" :required="!energyForm.isUsed" label="变比">
          <el-select v-if="!energyForm.isUsed" class="form-input" v-model="energyForm.variableRatio">
            <el-option v-for="item in variableRatioList" :key="item.value" :value="item.value" :label="item.label">
            </el-option>
          </el-select>
          <span v-else>{{i18n.getMsg('energyMgr.variableRatio.'+energyForm.variableRatio)}}</span>
        </el-form-item>
        <el-form-item label="仪表图片">
          <img-upload has-full-loading ref="energyUpload" v-model="energyForm.imgUrl" errorMsg="请上传图片格式的仪表图片" :auto-upload="false">
          </img-upload>
        </el-form-item>
        <el-form-item label-width="108px" label="部门-车间-工序">
          <el-cascader filterable clearable class="form-input" v-model="energyForm.deptProcess" :options="deptProcessList" separator="-"
            placeholder="请选择部门-车间-工序" :props="{value:'id',label:'name'}"></el-cascader>
        </el-form-item>
      </el-form>

      <div style="text-align:center">
        <el-button size="medium" type="primary" @click="ensure">
          <span v-if="type==='add'">新增</span>
          <span v-else>修改</span>
        </el-button>
      </div>
      </template>
    </div>
  `;

  return {
    props: {
      energy: {
        type: Object,
        default: function () {
          return null;
        }
      },
      type: {
        type: String,
        default: 'add'
      },
      dropdownOption: {
        type: Object,
        default: function () {
          return {};
        }
      }
    },

    data: function () {
      return {
        loading: false,
        energyForm: null,
        energyTypeList: i18n.getDropDown('energyMgr.energyType', [1, 2, 3]),
        variableRatioList: i18n.getDropDown('energyMgr.variableRatio', [1, 10, 15, 20, 30, 40]),
        deptProcessList: [],
        i18n: i18n
      };
    },

    created: function () {
      var self = this;
      this.loading = true;
      this.setWorkshopList().then(function (deptProcessMap) {
        if (self.type === 'add') {
          var energyForm = new EnergyModel();
          self.energyForm = energyForm;
          self.loading = false;
          return;
        }

        var energy = self.energy;
        return self.checkUsed(energy).then(function (isUsed) {
          var energyForm = new EnergyModel(self.energy, deptProcessMap, isUsed);
          self.energyForm = energyForm;
          self.loading = false;
        });
      }).catch(function () {
        self.loading = false;
      });
    },

    methods: {
      setWorkshopList: function () {
        var dropdownOption = this.dropdownOption;
        var deptProcessList = dropdownOption.deptProcessList;
        if (deptProcessList !== undefined) {
          this.deptProcessList = deptProcessList;
          return Promise.resolve(dropdownOption.deptProcessMap);
        }

        var self = this;
        return ajaxRequest('equipment/getDepartmentDropdown').then(function (deptProcessList) {
          deptProcessList = _.map(deptProcessList, function (deptProcess) {
            var workshops = deptProcess.workshops;
            workshops = _.map(workshops, function (workshop) {
              var processList = workshop.processList;
              processList = _.map(processList, function (processObj) {
                return {
                  id: String(processObj.processId),
                  name: processObj.processName
                };
              });
              return {
                id: workshop.id,
                name: workshop.workshopName,
                children: processList
              };
            });

            return {
              id: deptProcess.departmentCode,
              name: deptProcess.deptName,
              children: workshops
            };
          });

          var deptProcessMap = self.getDeptProcessMap(deptProcessList);

          dropdownOption.deptProcessMap = deptProcessMap;
          dropdownOption.deptProcessList = deptProcessList;
          self.deptProcessList = deptProcessList;
          return deptProcessMap;
        }).catch(function () {
          return [];
        });
      },

      checkUsed: function (energy) {
        return ajaxRequest('energy/checkEnergyIsUsed', {
          energyId: energy.no
        }).then(function (isUsed) {
          return isUsed;
        });
      },

      getDeptProcessMap: function (deptProcessList) {
        var deptProcessMap = {};
        for (var i = 0; i < deptProcessList.length; i++) {
          var dept = deptProcessList[i];
          var workshops = dept.children;
          for (var j = 0; j < workshops.length; j++) {
            var workshop = workshops[j];
            var processObjs = workshop.children;
            for (var k = 0; k < processObjs.length; k++) {
              var processObj = processObjs[k];
              deptProcessMap[processObj.id] = {
                deptId: dept.id,
                workshopId: workshop.id,
                processId: processObj.id
              }
            }
          }
        }
        return deptProcessMap;
      },

      ensure: function () {
        var energyForm = this.energyForm;
        var code = energyForm.checkValid();
        if (code !== '') {
          var msg = i18n.getMsg(`energyMgr.error.${code}`);
          this.$alert(msg, '信息');
          return;
        }

        if (this.type === 'add') {
          if (energyForm.energyType === 1) {
            var self = this;
            var variableRatio = energyForm.variableRatio;
            variableRatio = i18n.getMsg(`energyMgr.variableRatio.${variableRatio}`)
            this.$confirm(`请再次确认新增电表变比为${variableRatio}，该变比一旦确认后不能修改`, '再次确认').then(function () {
              self.toSave();
            }).catch(function () {});
            return;
          }
        }
        this.toSave();
      },

      toSave() {
        var self = this;
        var energyForm = this.energyForm;
        this.$refs['energyUpload'].submit().then(function () {
          if (self.type === 'add') {
            self.toAddEnergy(energyForm);
          } else {
            self.toUpdateEnergy(energyForm);
          }
        });
      },

      toAddEnergy: function (energyForm) {
        var postData = energyForm.getObject();

        this.loading = true;
        var self = this;
        ajaxRequest('energy/addEnergy', {
          jsonObject: JSON.stringify(postData)
        }).then(function () {
          self.loading = false;
          self.$alert('仪表新增成功', '信息', {
            callback: function () {
              self.$emit('save-success');
            }
          });
        }).catch(function () {
          self.loading = false;
        });
      },

      toUpdateEnergy: function (energyForm) {
        var postData = energyForm.getUpdateObject();

        this.loading = true;
        var self = this;
        ajaxRequest('energy/setEnergyWorkShop', postData).then(function () {
          self.loading = false;
          self.$alert('仪表修改成功', '信息', {
            callback: function () {
              self.$emit('save-success');
            }
          });
        }).catch(function () {
          self.loading = false;
        });
      }
    },

    components: {
      ImgUpload: ImgUpload
    },

    template: template
  };
}();
